package org.cleverframe.modules.erp.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.cleverframe.common.persistence.Page;
import org.cleverframe.common.service.BaseService;
import org.cleverframe.common.vo.AjaxMessage;
import org.cleverframe.modules.erp.ErpBeanNames;
import org.cleverframe.modules.erp.dao.RawMaterialInfoDao;
import org.cleverframe.modules.erp.dao.RawmaterialOutDao;
import org.cleverframe.modules.erp.entity.RawMaterialInfo;
import org.cleverframe.modules.erp.entity.RawmaterialOut;
import org.cleverframe.modules.sys.SysBeanNames;
import org.cleverframe.modules.sys.dao.DictDao;
import org.cleverframe.modules.sys.entity.Dict;
import org.cleverframe.modules.sys.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * 原料出库申请实体类Service<br>
 * @author LiZW
 * @version 2016年1月20日 下午10:19:39
 */
@Service(ErpBeanNames.RawmaterialOutService)
public class RawmaterialOutService extends BaseService
{
    /** 日志对象 */
    private final static Logger logger = LoggerFactory.getLogger(RawmaterialOutService.class);
    
    /** 审核人的字典类型 */
    public static final String AUDITOR_DICT_TYPE = "原料出库申请审核流程-车间加工";
    /** 审核人的字典名称 */
    public static final String AUDITOR_DICT_KEY = "财务部门审核";
    
    @Autowired
    @Qualifier(ErpBeanNames.RawmaterialOutDao)
    private RawmaterialOutDao rawmaterialOutDao;
    
    @Autowired
    @Qualifier(ErpBeanNames.RawMaterialInfoDao)
    private RawMaterialInfoDao rawMaterialInfoDao;
    
    @Autowired
    @Qualifier(SysBeanNames.DictDao)
    private DictDao dictDao;
    
    /**
     * 分页查询原料出库单<br>
     * @param page 分页数据
     * @param outType 查询参数：出库类型
     * @param outNo 查询参数：出库单编号
     * @param name 查询参数：原料名称
     * @param specification 查询参数：原料规格
     * @param auditorState 查询参数：审核状态
     * @param startDate 查询参数：出库时间(最小)
     * @param endDate 查询参数：出库时间(最大)
     * @return 分页数据
     */
    public Page<Map<Object, Object>> findRawmaterialOutByPage(
            Page<Map<Object, Object>> page, 
            String rawmaterialCode, 
            String outType, 
            String outNo, 
            String name, 
            String specification, 
            String auditorState,
            Date startDate, 
            Date endDate)
    {
        return rawmaterialOutDao.findRawmaterialOutByPage(page, rawmaterialCode, outType, outNo, name, specification, auditorState, startDate, endDate);
    }
    
    /**
     * 根据原料出库单编号或原料名称，模糊查询原料出库单
     * @param page 
     * @param q 查询参数
     * @return
     */
    public Page<Map<Object, Object>> findRawmaterialOutByCombobox(Page<Map<Object, Object>> page, String q)
    {
        return rawmaterialOutDao.findRawmaterialOutByCombobox(page, q);
    }
    
    /**
     * 查询当前用户需要审核的原料出库单<br>
     * @param page 分页数据
     * @param outType 查询参数：出库类型
     * @param outNo 查询参数：出库单编号
     * @param name 查询参数：原料名称
     * @param specification 查询参数：原料规格
     * @param auditorState 查询参数：审核状态
     * @param startDate 查询参数：出库时间(最小)
     * @param endDate 查询参数：出库时间(最大)
     * @param userId 查询参数：用户ID
     * @return 分页数据
     */
    public Page<Map<Object, Object>> findAuditRawmaterialOutByPage(
            Page<Map<Object, Object>> page, 
            String outType, 
            String outNo, 
            String name, 
            String specification, 
            String auditorState,
            Date startDate, 
            Date endDate,
            Long userId)
    {
        return rawmaterialOutDao.findAuditRawmaterialOutByPage(page, outType, outNo, name, specification, auditorState, startDate, endDate, userId);
    }
    
    /**
     * 新增原料出库申请单<br>
     * 1.初始化审核时填写的数据<br>
     * 2.验证原料存在<br>
     * 3.验证 “原料”、“流程审核人” 存在<br>
     * 4.生成原料出库申请单号码<br>
     * TODO 5.验证“订单编号”订单存在，和“订单编号”与“是否先下订单后原料出库”关系<br>
     */
    public synchronized boolean addRawmaterialOut(RawmaterialOut rawmaterialOut, AjaxMessage message)
    {
        // 初始化审核时填写的数据
        rawmaterialOut.setAuditorState(RawmaterialOut.PENDING_AUDIT);
        rawmaterialOut.setUnitPrice(new BigDecimal(0));
        rawmaterialOut.setAggregateAmount(new BigDecimal(0));
        rawmaterialOut.setIsInvoice(RawmaterialOut.INVOICE_YES);
        rawmaterialOut.setIsHistory(RawmaterialOut.HISTORY_NO);
        rawmaterialOut.setIsChange(RawmaterialOut.CHANGE_NO);
        
        // 验证
        RawMaterialInfo rawMaterialInfo = rawMaterialInfoDao.getRawMaterialInfoByCode(rawmaterialOut.getRawmaterialCode());
        if (rawMaterialInfo == null)
        {
            message.setMessage("原料[" + rawmaterialOut.getName() + "]不存在");
            return false;
        }
        
        User user = rawmaterialOutDao.getHibernateDao().getEntity(User.class, rawmaterialOut.getAuditorId());
        if (user == null)
        {
            message.setMessage("流程审核人不存在");
            return false;
        }
        
        // 生成原料出库申请单号码
        String outMaxNo = rawmaterialOutDao.getOutMaxNo();
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < RawmaterialOut.NO_NUMBER_LENGTH; i++)
        {
            str.append('0');
        }
        if(StringUtils.isBlank(outMaxNo))
        {
            str.append('1');
        }
        else
        {
            outMaxNo = outMaxNo.replace(RawmaterialOut.NO_PREFIX, "").replace(RawmaterialOut.NO_SUFFIX, "");
            int max = NumberUtils.toInt(outMaxNo, 0) + 1;
            str.append(max);
        }
        outMaxNo = str.toString().substring(str.length() - RawmaterialOut.NO_NUMBER_LENGTH);
        outMaxNo = RawmaterialOut.NO_PREFIX + outMaxNo + RawmaterialOut.NO_SUFFIX;
        rawmaterialOut.setOutNo(outMaxNo);
        
        // 保存数据
        rawmaterialOutDao.getHibernateDao().save(rawmaterialOut);
        return true;
    }
    
    /**
     * 更新原料出库申请单<br>
     * 1.验证修改的原料出库申请单存在，而且审核状态只能是：(1：等待审核；4：审核完成-驳回)<br>
     * 2.初始化审核时填写的数据<br>
     * 3.验证原料存在<br>
     * 4.验证 “原料”、“流程审核人” 存在<br>
     * 5.原料出库申请单编号不能修改<br>
     * TODO 6.验证“订单编号”订单存在，和“订单编号”与“是否先下订单后原料出库”关系<br>
     * */
    public boolean updateRawmaterialOut(RawmaterialOut rawmaterialOut, AjaxMessage message)
    {
        RawmaterialOut oldRawmaterialOut = rawmaterialOutDao.getHibernateDao().get(rawmaterialOut.getId());
        if (oldRawmaterialOut == null)
        {
            message.setMessage("原料出库申请单不存在");
            return false;
        }
        if (new Character(RawmaterialOut.PENDING_AUDIT).equals(oldRawmaterialOut.getAuditorState()) == false
                && new Character(RawmaterialOut.AUDIT_REJECT).equals(oldRawmaterialOut.getAuditorState()) == false)
        {
            message.setMessage("原料出库申请单审核状态必须是“等待审核”、“驳回”才能修改");
            return false;
        }
        
        if (oldRawmaterialOut.getOutNo().equals(oldRawmaterialOut.getOutNo()) == false)
        {
            message.setMessage("不能修改原料出库申请单编号");
            return false;
        }
        
        // 初始化审核时填写的数据
        rawmaterialOut.setAuditorState(RawmaterialOut.PENDING_AUDIT);
        rawmaterialOut.setUnitPrice(new BigDecimal(0));
        rawmaterialOut.setAggregateAmount(new BigDecimal(0));
        rawmaterialOut.setIsInvoice(RawmaterialOut.INVOICE_YES);
        rawmaterialOut.setIsHistory(RawmaterialOut.HISTORY_NO);
        rawmaterialOut.setIsChange(oldRawmaterialOut.getIsChange());
        
        // 验证
        RawMaterialInfo rawMaterialInfo = rawMaterialInfoDao.getRawMaterialInfoByCode(rawmaterialOut.getRawmaterialCode());
        if (rawMaterialInfo == null)
        {
            message.setMessage("原料[" + rawmaterialOut.getName() + "]不存在");
            return false;
        }
        
        User user = rawmaterialOutDao.getHibernateDao().getEntity(User.class, rawmaterialOut.getAuditorId());
        if (user == null)
        {
            message.setMessage("流程审核人不存在");
            return false;
        }
        
        // 更新数据
        rawmaterialOutDao.getHibernateDao().getSession().evict(oldRawmaterialOut);
        rawmaterialOutDao.getHibernateDao().getSession().update(rawmaterialOut);
        return true;
    }
    
    /**
     * 删除原料出库申请单<br>
     * 1.验证修改的原料出库申请单存在，而且审核状态只能是：(1：等待审核；4：审核完成-驳回)<br>
     * 2.删除必须删除历史单<br>
     * */
    public boolean deleteRawmaterialOut(RawmaterialOut rawmaterialOut, AjaxMessage message)
    {
        // 验证
        RawmaterialOut oldRawmaterialOut = rawmaterialOutDao.getHibernateDao().get(rawmaterialOut.getId());
        if (oldRawmaterialOut == null)
        {
            message.setMessage("原料出库申请单不存在");
            return false;
        }
        if (new Character(RawmaterialOut.PENDING_AUDIT).equals(oldRawmaterialOut.getAuditorState()) == false
                && new Character(RawmaterialOut.AUDIT_REJECT).equals(oldRawmaterialOut.getAuditorState()) == false)
        {
            message.setMessage("原料出库申请单审核状态必须是“等待审核”、“驳回”才能删除");
            return false;
        }

        // 删除历史单
        String outNo = oldRawmaterialOut.getOutNo() + RawmaterialOut.HISTORY_NO_SUFFIX;
        RawmaterialOut historyRawmaterialOut = rawmaterialOutDao.getRawmaterialOutByOutNo(outNo);
        if (historyRawmaterialOut != null)
        {
            rawmaterialOutDao.getHibernateDao().delete(historyRawmaterialOut);
        }
        // 删除
        rawmaterialOutDao.getHibernateDao().delete(oldRawmaterialOut);
        return true;
    }
    
    /**
     * 变更原料出库申请单<br>
     * 1.验证修改的原料出库申请单存在，而且审核状态只能是：(3：审核完成-通过)<br>
     * 2.验证变更的申请单 “原料”、“流程审核人” 存在<br>
     * 3.初始化变更的申请单审核时填写的数据<br>
     * 4.修改原料出库申请单原单的原料编号(增加历史信息)，并且设置变更的申请单的编号<br>
     * 5.数据库保存变更的申请单<br>
     * */
    public boolean changeRawmaterialOut(RawmaterialOut rawmaterialOut, AjaxMessage message)
    {
        // 验证
        RawmaterialOut oldRawmaterialOut = rawmaterialOutDao.getHibernateDao().get(rawmaterialOut.getId());
        if (oldRawmaterialOut == null)
        {
            message.setMessage("原料出库申请单不存在");
            return false;
        }
        if (new Character(RawmaterialOut.AUDIT_PASS).equals(oldRawmaterialOut.getAuditorState()) == false)
        {
            message.setMessage("原料出库申请单审核状态必须是“通过”才能变更");
            return false;
        }
        
        // 验证
        RawMaterialInfo rawMaterialInfo = rawMaterialInfoDao.getRawMaterialInfoByCode(rawmaterialOut.getRawmaterialCode());
        if (rawMaterialInfo == null)
        {
            message.setMessage("原料[" + rawmaterialOut.getName() + "]不存在");
            return false;
        }
        
        User user = rawmaterialOutDao.getHibernateDao().getEntity(User.class, rawmaterialOut.getAuditorId());
        if (user == null)
        {
            message.setMessage("流程审核人不存在");
            return false;
        }
        
        // 初始化审核时填写的数据
        rawmaterialOut.setAuditorState(RawmaterialOut.PENDING_AUDIT);
        rawmaterialOut.setUnitPrice(new BigDecimal(0));
        rawmaterialOut.setAggregateAmount(new BigDecimal(0));
        rawmaterialOut.setIsInvoice(RawmaterialOut.INVOICE_YES);
        rawmaterialOut.setIsHistory(RawmaterialOut.HISTORY_NO);
        // 设置已经变更
        rawmaterialOut.setIsChange(RawmaterialOut.CHANGE_YES);
        
        // 数据库保存变更的申请单
        rawmaterialOutDao.getHibernateDao().getSession().evict(oldRawmaterialOut);
        rawmaterialOutDao.getHibernateDao().getSession().update(rawmaterialOut);
        // 修改原料出库申请单原单的原料编号(增加历史信息)
        String outNo = oldRawmaterialOut.getOutNo() + RawmaterialOut.HISTORY_NO_SUFFIX;
        RawmaterialOut historyRawmaterialOut = rawmaterialOutDao.getRawmaterialOutByOutNo(outNo);
        if (historyRawmaterialOut != null)
        {
            rawmaterialOutDao.getHibernateDao().getSession().evict(historyRawmaterialOut);
            oldRawmaterialOut.setId(historyRawmaterialOut.getId());
        }
        else
        {
            oldRawmaterialOut.setId(null);
        }
        oldRawmaterialOut.setIsHistory(RawmaterialOut.HISTORY_YES);
        oldRawmaterialOut.setOutNo(outNo);
        if (historyRawmaterialOut == null)
        {
            rawmaterialOutDao.getHibernateDao().getSession().save(oldRawmaterialOut);
        }
        else
        {
            rawmaterialOutDao.getHibernateDao().getSession().update(oldRawmaterialOut);
        }
        return true;
    }
    
    /**
     * 审核原料出库申请单--通过处理<br>
     * 1.验证修改的原料入库申请单存在，而且审核状态只能是：(1：等待审核；2：审核中-已经审核过但是没有完成)<br>
     * 2.验证 “原料”、“流程审核人” 存在<br>
     * 3.验证审核数据正确<br>
     * 4.修改审核状态<br>
     * */
    public synchronized boolean auditResultPass(RawmaterialOut rawmaterialOut, AjaxMessage message)
    {
        // 验证
        RawmaterialOut oldRawmaterialOut = rawmaterialOutDao.getHibernateDao().get(rawmaterialOut.getId());
        if (oldRawmaterialOut == null)
        {
            message.setMessage("原料出库申请单不存在");
            return false;
        }
        if (new Character(RawmaterialOut.PENDING_AUDIT).equals(oldRawmaterialOut.getAuditorState()) == false
            && new Character(RawmaterialOut.AUDIT_ING).equals(oldRawmaterialOut.getAuditorState()) == false)
        {
            message.setMessage("原料出库申请单审核状态必须是“等待审核”、“审核中”才能审核");
            return false;
        }
        
        // 验证
        RawMaterialInfo rawMaterialInfo = rawMaterialInfoDao.getRawMaterialInfoByCode(rawmaterialOut.getRawmaterialCode());
        if (rawMaterialInfo == null)
        {
            message.setMessage("原料[" + rawmaterialOut.getName() + "]不存在");
            return false;
        }
        
        User user = rawmaterialOutDao.getHibernateDao().getEntity(User.class, rawmaterialOut.getAuditorId());
        if (user == null)
        {
            message.setMessage("流程审核人不存在");
            return false;
        }
        
        if (new Character(RawmaterialOut.OUT_GOING).equals(rawmaterialOut.getOutType()))
        {
            // 验证审核数据
            if (rawmaterialOut.getUnitPrice().longValue() < 0L)
            {
                message.setMessage("原料外发加工单价不能小于0");
                return false;
            }
            
            // 审核通过
            BigDecimal aggregateAmount = rawmaterialOut.getUnitPrice().multiply(rawmaterialOut.getQuantity());
            rawmaterialOut.setAggregateAmount(aggregateAmount);
            if (rawmaterialOut.getAggregateAmount().longValue() < 0L)
            {
                message.setMessage("原料外发加工应付金额不能小于0");
                return false;
            }
        }
        rawmaterialOut.setAuditorState(RawmaterialOut.AUDIT_PASS);
        rawmaterialOut.setIsHistory(RawmaterialOut.HISTORY_NO);
        rawmaterialOut.setIsChange(oldRawmaterialOut.getIsChange());
        // TODO 减少库存
        
        //更新
        rawmaterialOutDao.getHibernateDao().getSession().evict(oldRawmaterialOut);
        rawmaterialOutDao.getHibernateDao().update(rawmaterialOut);
        return true;
    }
    
    /**
     * 审核原料出库申请单--驳回处理<br>
     * 1.验证修改的原料入库申请单存在，而且审核状态只能是：(1：等待审核；2：审核中-已经审核过但是没有完成)<br>
     * 2.验证 “原料”、“流程审核人” 存在<br>
     * 3.初始化审核数据正确<br>
     * 4.修改审核状态<br>
     * */
    public synchronized boolean auditResultReject(RawmaterialOut rawmaterialOut, AjaxMessage message)
    {
        // 验证
        RawmaterialOut oldRawmaterialOut = rawmaterialOutDao.getHibernateDao().get(rawmaterialOut.getId());
        if (oldRawmaterialOut == null)
        {
            message.setMessage("原料出库申请单不存在");
            return false;
        }
        if (new Character(RawmaterialOut.PENDING_AUDIT).equals(oldRawmaterialOut.getAuditorState()) == false
            && new Character(RawmaterialOut.AUDIT_ING).equals(oldRawmaterialOut.getAuditorState()) == false)
        {
            message.setMessage("原料出库申请单审核状态必须是“等待审核”、“审核中”才能审核");
            return false;
        }
        
        // 验证
        RawMaterialInfo rawMaterialInfo = rawMaterialInfoDao.getRawMaterialInfoByCode(rawmaterialOut.getRawmaterialCode());
        if (rawMaterialInfo == null)
        {
            message.setMessage("原料[" + rawmaterialOut.getName() + "]不存在");
            return false;
        }
        
        User user = rawmaterialOutDao.getHibernateDao().getEntity(User.class, rawmaterialOut.getAuditorId());
        if (user == null)
        {
            message.setMessage("流程审核人不存在");
            return false;
        }
        
        // 初始化审核时填写的数据
        rawmaterialOut.setUnitPrice(new BigDecimal(0));
        rawmaterialOut.setAggregateAmount(new BigDecimal(0));
        rawmaterialOut.setIsInvoice(RawmaterialOut.INVOICE_YES);
        rawmaterialOut.setIsHistory(RawmaterialOut.HISTORY_NO);
        rawmaterialOut.setIsChange(oldRawmaterialOut.getIsChange());
        
        // 设置审核驳回
        rawmaterialOut.setAuditorState(RawmaterialOut.AUDIT_REJECT);

        //更新
        rawmaterialOutDao.getHibernateDao().getSession().evict(oldRawmaterialOut);
        rawmaterialOutDao.getHibernateDao().update(rawmaterialOut);
        return true;
    }
    
    /**
     * 根据原料出库申请单编号查询申请单
     * @param warehouseNo 查询参数：原料出库申请单编号
     * @return 原料出库申请单以及关联信息
     */
    public Map<String, Object> getRawmaterialOutByNo(String outNo)
    {
        return rawmaterialOutDao.getRawmaterialOutByNo(outNo);
    }
    
    /**
     * 获取原料出(车间加工)库审核人<br>
     * */
    public User getAuditorByRawmaterialOut()
    {
        Dict dict = dictDao.getDictByTypeAndkey(AUDITOR_DICT_TYPE, AUDITOR_DICT_KEY);
        if (dict == null)
        {
            logger.error("获取原料出库(车间加工)审核人出错！请在配置字典[type=" + AUDITOR_DICT_TYPE + ",key=" + AUDITOR_DICT_KEY + "]");
            return null;
        }
        long userId = NumberUtils.toLong(dict.getDictValue(), -1L);
        if (userId == -1L)
        {
            logger.error("获取原料出库(车间加工)审核人出错！请在配置字典[type=" + AUDITOR_DICT_TYPE + ",key=" + AUDITOR_DICT_KEY + "]的值是可用的用户ID！");
            return null;
        }
        return rawmaterialOutDao.getHibernateDao().getEntity(User.class, userId);
    }
}
